﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AnnotateMe.Interfaces;

namespace AnnotateMe.Logic
{
    /// <summary>
    /// Parses simple text query string into pairs (label -> annotation).
    /// Assumes that annotations are passed in round brackets.
    /// Example:  "hello(world)"   turns into "hello" annotated with "world"
    /// </summary>
    public class SimpleTextQueryParser
    {
        public IEnumerable<Tuple<string,string>> Parse(string query)
        {
            string currentWord = string.Empty;
            string currentAnnotation = string.Empty;
            bool inAnnotation = false;
            
            foreach (var c in query)
            {
                if (c == ' ' && !inAnnotation)
                {
                    if (currentWord != string.Empty)
                    {
                        yield return new Tuple<string, string>(currentWord, currentAnnotation);
                        currentAnnotation = string.Empty;
                        currentWord = string.Empty;
                    }

                    yield return new Tuple<string, string>(" ", string.Empty);
                    continue;
                }

                if (c == '(' && !inAnnotation)
                {
                    inAnnotation = true;
                    continue;
                }

                if (c == ')' && inAnnotation)
                {
                    inAnnotation = false;
                    yield return new Tuple<string, string>(currentWord, currentAnnotation);

                    currentWord = string.Empty;
                    currentAnnotation = string.Empty;
                    continue;
                }

                if (inAnnotation)
                {
                    currentAnnotation += c;
                }
                else
                {
                    currentWord += c;
                }
            }

            if (inAnnotation)
            {
                throw new ArgumentException("Wrong query format", "query");
            }
            else
            {
                if (currentWord != string.Empty)
                {
                    yield return new Tuple<string, string>(currentWord, currentAnnotation);
                }
            }
        }
    }
}
